package com.hw.one.peach.core.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hw.one.dam2.common.DamConstant;
import com.hw.one.dam2.dao.IPatrolDeviceDao;
import com.hw.one.dam2.dao.IPatrolTrackDao;
import com.hw.one.dam2.dao.IRegionSiteDao;
import com.hw.one.dam2.param.MovingDeviceParam;
import com.hw.one.dam2.po.PatrolDataPo;
import com.hw.one.dam2.util.CalendarUtil;
import com.hw.one.peach.core.util.MovingSourceUtil;
import com.hw.one.peach.core.util.PointCalUtil;
import com.mongodb.DBObject;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/8/10.
 */
@Service
public class MovingSourceService implements IMovingSourceService {

    // 设备基础信息
    @Resource
    private IPatrolDeviceDao patrolDeviceDao;

    // 设备轨迹信息
    @Resource
    private IPatrolTrackDao patrolTrackDao;

    @Resource
    private IRegionSiteDao regionSiteDao;

    @Override
    public Object findMovingSource(Map<String, Object> paramMap) throws Exception {
        String userRegionCode = (String) paramMap.get("regionCode");
        String regionName = (String) paramMap.get("regionName");

        /**
         * 根据当前登录用户区域，查询该区域的上级区域
         */
        List<Map<String, Object>> parentRegionList = regionSiteDao.findParentRegionInfoByRegionCode(userRegionCode);
        // 地图的中心点位
        JSONObject centerPointObj = new JSONObject();
        for (Map<String, Object> parentRegionMap : parentRegionList) {
            String regionCode = String.valueOf(parentRegionMap.get("regionCode"));
            if (userRegionCode.equals(regionCode)) {
                centerPointObj.put("lng", parentRegionMap.get("longitude"));
                centerPointObj.put("lat", parentRegionMap.get("latitude"));
            }
        }
        // regionCode 必须，deviceType 必须
        List<Map<String, Object>> deviceInfoList = patrolDeviceDao.findPatrolDeviceInfoByRegionCode(paramMap);

        // 循环取出设备编码
        List<String> deviceCodeList = new ArrayList<>();
        Map<String,String> codeWithAttribute = new HashMap<>();
        // 处理数据
        dealDeviceInfoData(deviceInfoList, deviceCodeList, codeWithAttribute);

        MovingDeviceParam deviceParam = new MovingDeviceParam();
        deviceParam.setDeviceCodeList(deviceCodeList);
        deviceParam.setDeviceStatus((String) paramMap.get("deviceStatus"));
        // 查询设备实时轨迹信息
        List<PatrolDataPo> trackList = patrolTrackDao.findPatrolTrackRealDataByDeviceCodesAndStatus(deviceParam);
        Date nowDate = CalendarUtil.getDateByString(CalendarUtil.getDateFormat(new Date(), DamConstant.ALL_SDF_YMD), DamConstant.ALL_SDF_YMD);
        // 循环数据，组装成前段需要的格式
        JSONArray returnArr = dealMovingSourceDataList(trackList, codeWithAttribute);

        JSONObject returnMap = new JSONObject();
        returnMap.put("siteList", returnArr);        //返回的数据
        returnMap.put("centerSite", centerPointObj);  //中心城市点位
        returnMap.put("centerName", regionName);
        return returnMap;
    }

    @Override
    public Object findMovingSourceByLoc(Map<String, Object> paramMap) throws Exception {
        String userRegionCode = (String) paramMap.get("regionCode");
        String regionName = (String) paramMap.get("regionName");
        String longitude = (String) paramMap.get("longitude");
        String latitude = (String) paramMap.get("latitude");
        String radius = (String) paramMap.get("radius");
        // 地图的中心点位
        JSONObject centerPointObj = new JSONObject();
        if (StringUtils.isEmpty(longitude) && StringUtils.isEmpty(latitude)) {
            /**
             * 根据当前登录用户区域，查询该区域的上级区域
             */
            List<Map<String, Object>> parentRegionList = regionSiteDao.findParentRegionInfoByRegionCode(userRegionCode);

            for (Map<String, Object> parentRegionMap : parentRegionList) {
                String regionCode = String.valueOf(parentRegionMap.get("regionCode"));
                if (userRegionCode.equals(regionCode)) {
                    centerPointObj.put("lng", parentRegionMap.get("longitude"));
                    centerPointObj.put("lat", parentRegionMap.get("latitude"));
                }
            }
        }else {
            centerPointObj.put("lng", longitude);
            centerPointObj.put("lat", latitude);
        }
        // regionCode 必须，deviceType 必须
        List<Map<String, Object>> deviceInfoList = patrolDeviceDao.findPatrolDeviceInfoByRegionCode(paramMap);

        // 循环取出设备编码
        List<String> deviceCodeList = new ArrayList<>();
        Map<String,String> codeWithAttribute = new HashMap<>();
        // 处理数据
        dealDeviceInfoData(deviceInfoList, deviceCodeList, codeWithAttribute);

        MovingDeviceParam deviceParam = new MovingDeviceParam();
        deviceParam.setDeviceCodeList(deviceCodeList);
        deviceParam.setDeviceStatus((String) paramMap.get("deviceStatus"));
        // 此处的半径单位是米，需要除以赤道半径
        deviceParam.setRadius(Double.valueOf(radius) / 6378137.0);
        double[] location = new double[]{centerPointObj.getDouble("lng"), centerPointObj.getDouble("lat")};
        deviceParam.setLocation(location);
        // 查询设备实时轨迹信息
        List<PatrolDataPo> trackList = patrolTrackDao.findPatrolTrackRealDataByDeviceCodesAndLocScope(deviceParam);
        Date nowDate = CalendarUtil.getDateByString(CalendarUtil.getDateFormat(new Date(), DamConstant.ALL_SDF_YMD), DamConstant.ALL_SDF_YMD);
        // 循环数据，组装成前段需要的格式
        JSONArray returnArr = dealMovingSourceDataList(trackList, codeWithAttribute);

        JSONObject returnMap = new JSONObject();
        returnMap.put("siteList", returnArr);        //返回的数据
        returnMap.put("centerSite", centerPointObj);  //中心城市点位
        returnMap.put("centerName", regionName);
        return returnMap;
    }

    @Override
    public Object findSelectBoxCar(Map<String, Object> paramMap) throws Exception {
        // 前端取点的值
        String lngSets = (String) paramMap.get("lngSets");
        String latSets = (String) paramMap.get("latSets");
        String deviceType = (String) paramMap.get("deviceType");
        String deviceStatus = (String) paramMap.get("deviceStatus");
        String regionName = (String) paramMap.get("regionName");
        String regionCode = (String) paramMap.get("regionCode");
        String startTime = (String) paramMap.get("startTime");
        String endTime = (String) paramMap.get("endTime");

        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("regionCode", regionCode);
        searchMap.put("deviceType", deviceType);
        // regionCode 必须，deviceType 必须
        List<Map<String, Object>> deviceInfoList = patrolDeviceDao.findPatrolDeviceInfoByRegionCode(searchMap);

        // 循环取出设备编码
        List<String> deviceCodeList = new ArrayList<>();
        Map<String,String> codeWithAttribute = new HashMap<>();
        // 处理数据
        dealDeviceInfoData(deviceInfoList, deviceCodeList, codeWithAttribute);
        MovingDeviceParam deviceParam = new MovingDeviceParam();
        deviceParam.setDeviceCodeList(deviceCodeList);
        deviceParam.setDeviceStatus(deviceStatus);
        List<double[]> locationList = new ArrayList<>();

        // 所选区域框
        String[] latSet = latSets.split(",");
        String[] lngSet = lngSets.split(",");
        for (int i=0; i<latSet.length; i++) {
            double[] locations = new double[2];
            String lng = lngSet[i];
            String lat = latSet[i];
            locations[0] = Double.valueOf(lng);
            locations[1] = Double.valueOf(lat);
            locationList.add(locations);
        }
        // 框选区域点位小于3返回空值
        if (locationList.size() < 3) {
            return  new JSONArray();
        }
        deviceParam.setLocationList(locationList);

        // 查询设备实时轨迹信息
        List<PatrolDataPo> trackList = patrolTrackDao.findPatrolTrackRealDataByLocation(deviceParam);

        deviceParam.setStartTime(startTime);
        deviceParam.setEndTime(endTime);
        // 根据时间和编码查询此时间段设备是否有数据
        List<Map> groupList = patrolTrackDao.findPatrolTrackByTimeAndGroupByCodes(deviceParam);
        List<String> groupCodeList = new ArrayList<>();
        for (Map group : groupList) {
            groupCodeList.add((String) group.get("_id"));
        }

        // 循环数据，组装成前段需要的格式
        // 判断是否在所选区域内
        JSONArray returnArr = dealMovingSourceDataList(trackList, codeWithAttribute, groupCodeList);

        return returnArr;
    }


    /**
     * 处理数据封装用
     *
     * @param deviceInfoList
     * @param deviceCodeList
     * @param codeWithAttribute
     */
    private void dealDeviceInfoData(List<Map<String, Object>> deviceInfoList, List<String> deviceCodeList,
                                    Map<String, String> codeWithAttribute) {
        for (Map<String, Object> deviceInfo : deviceInfoList) {
            deviceCodeList.add((String) deviceInfo.get("deviceCode"));
            codeWithAttribute.put((String) deviceInfo.get("deviceCode") + "deviceName", String.valueOf(deviceInfo.get("deviceName")));
            codeWithAttribute.put((String) deviceInfo.get("deviceCode") + "companyName", String.valueOf(deviceInfo.get("companyName")));
            codeWithAttribute.put((String) deviceInfo.get("deviceCode") + "carCode", String.valueOf(deviceInfo.get("carCode")));
            codeWithAttribute.put((String) deviceInfo.get("deviceCode") + "deviceType", String.valueOf(deviceInfo.get("deviceType")));
        }
    }


    /**
     * 循环移动源数据，封装成返回格式
     *
     * @param trackList
     * @param codeWithAttribute
     * @return
     * @throws Exception
     */
    private JSONArray dealMovingSourceDataList(List<PatrolDataPo> trackList, Map<String,String> codeWithAttribute,
                                               List<String> groupList) throws Exception {
        JSONArray returnArr = new JSONArray();
        if (trackList != null && trackList.size() > 0) {
            for (PatrolDataPo track : trackList) {
                String deviceCode = track.getDEVICECODE();
                JSONObject obj = new JSONObject();
                String status;
                if (groupList.contains(deviceCode)) {
                    status = "1111"; // 数据正常
                }else {
                    status = "0000"; // 数据异常
                }
                obj.put("siteStatus", status);
                obj.put("deviceCode", deviceCode);
                obj.put("deviceName", codeWithAttribute.get(deviceCode + "deviceName"));
                obj.put("companyName", codeWithAttribute.get(deviceCode + "companyName"));
                obj.put("carCode", codeWithAttribute.get(deviceCode + "carCode"));
                obj.put("lat",track.getLoc()[1]);
                obj.put("lng",track.getLoc()[0]);
                obj.put("deviceStatus",track.getDEVCIESTATUS() == null ? "-" : MovingSourceUtil.changeDeviceStatus(track.getDEVCIESTATUS()));
                obj.put("runStatus",track.getRUNSTATUS() == null ? "-" : MovingSourceUtil.changeRunningStatus(track.getRUNSTATUS()));
                obj.put("alarmStatus",track.getALARMSTATUS() == null ?"-" : MovingSourceUtil.changeAlarmStatus(track.getALARMSTATUS()));
                String deviceTypeCode = codeWithAttribute.get(deviceCode + "deviceType");
                if ("4".equals(deviceTypeCode)) {
                    obj.put("deviceType", "渣土车");
                    obj.put("deviceTypeCode", "4");
                }else {
                    obj.put("deviceType", "-");
                    obj.put("deviceTypeCode", "-");
                }
                returnArr.add(obj);
            }
        }
        return returnArr;
    }
    /**
     * 循环移动源数据，封装成返回格式
     * @param trackList
     * @param codeWithAttribute
     * @return
     * @throws Exception
     */
    private JSONArray dealMovingSourceDataList(List<PatrolDataPo> trackList, Map<String,String> codeWithAttribute) throws Exception {
        JSONArray returnArr = new JSONArray();
        Date nowDate = CalendarUtil.getDateByString(CalendarUtil.getDateFormat(new Date(), DamConstant.ALL_SDF_YMD), DamConstant.ALL_SDF_YMD);
        if (trackList != null && trackList.size() > 0) {
            for (PatrolDataPo track : trackList) {
                JSONObject obj = new JSONObject();
                String monitorTime = track.getMONITORTIME();
                Date monitorDate = CalendarUtil.getDateByString(monitorTime, DamConstant.SDF_YMD_HMS);
                // 判断时间比当前时间，如果小于今天00的时间，就认为不在线
                String status;
                if (monitorDate.getTime() > nowDate.getTime()) {
                    status = "1111"; // 数据正常
                }else {
                    status = "0000"; // 数据异常
                }
                obj.put("siteStatus", status);
                String deviceCode = track.getDEVICECODE();
                obj.put("deviceCode", deviceCode);
                obj.put("deviceName", codeWithAttribute.get(deviceCode + "deviceName"));
                obj.put("companyName", codeWithAttribute.get(deviceCode + "companyName"));
                obj.put("carCode", codeWithAttribute.get(deviceCode + "carCode"));
                obj.put("lat",track.getLoc()[1]);
                obj.put("lng",track.getLoc()[0]);
                obj.put("deviceStatus",track.getDEVCIESTATUS() == null ? "-" : MovingSourceUtil.changeDeviceStatus(track.getDEVCIESTATUS()));
                obj.put("runStatus",track.getRUNSTATUS() == null ? "-" : MovingSourceUtil.changeRunningStatus(track.getRUNSTATUS()));
                obj.put("alarmStatus",track.getALARMSTATUS() == null ?"-" : MovingSourceUtil.changeAlarmStatus(track.getALARMSTATUS()));
                String deviceTypeCode = codeWithAttribute.get(deviceCode + "deviceType");
                if ("4".equals(deviceTypeCode)) {
                    obj.put("deviceType", "渣土车");
                    obj.put("deviceTypeCode", "4");
                }else {
                    obj.put("deviceType", "-");
                    obj.put("deviceTypeCode", "-");
                }
                returnArr.add(obj);
            }
        }
        return returnArr;
    }


}
